﻿@using System.Linq; 
@model IEnumerable<Fap.Core.Infrastructure.Model.FapFormulaCase>
@{ 
    string tableName = ViewBag.Tn;
    string mappingTableName = ViewBag.Mtn;
    IEnumerable<Fap.Core.Infrastructure.Metadata.FapColumn> columns = _dbContext.Columns(tableName).Where(c => c.IsDefaultCol == 0);
}
@*<link href="~/Content/css/codemirror/codemirror.css" rel="stylesheet" />
    <link rel="stylesheet" href="~/Content/css/codemirror/theme/xq-light.css"/>
    <script src="~/Content/js/codemirror/codemirror.js"></script>
    <script src="~/Content/js/codemirror/mode/sql/sql.js"></script>*@
<div class="row">
    <div class=" col-xs-12 col-sm-3">
        <div class="widget-box">
            <div class="widget-header widget-header-small widget-header-flat">
                <h6 class="widget-title">公式套</h6>

                <div class="widget-toolbar">
                    <a href="javascript:void(0)" title="添加" id="btnAddFormulaCase">
                        <i class="ace-icon fa fa-plus "></i>
                    </a>
                    <a href="javascript:void(0)" title="编辑" id="btnEditFormulaCase">
                        <i class="ace-icon fa fa-pencil "></i>
                    </a>
                    <a href="javascript:void(0)" title="删除" id="btnDelFormulaCase">
                        <i class="ace-icon fa fa-trash-o red"></i>
                    </a>
                </div>

            </div>
            <div class="widget-body">
                <div class="widget-main no-padding">
                    <select class="form-control" id="field-select-formulacase">
                        <option value="">--请选择--</option>
                        @foreach (var item in Model)
                        {
                            <option value="@item.Fid">@item.FcName</option>
                        }
                    </select>
                </div>
            </div>
        </div>
        <div class="widget-box">
            <div class="widget-header widget-header-small widget-header-flat">
                <h6 class="widget-title">公式项</h6>
                <div class="widget-toolbar">
                    <a href="javascript:void(0)" title="添加" id="btnAddFormulaItem">
                        <i class="ace-icon fa fa-plus"></i>
                    </a>
                    <a href="javascript:void(0)" title="保存" id="btnSaveFormulaItem">
                        <i class="ace-icon fa fa-floppy-o"></i>
                    </a>
                </div>
            </div>
            <div class="widget-body">
                <div class="widget-main no-padding scrollable" data-size="360" id="divformulaitems" style="height:360px">
                    <ul id="formulaItems" class="item-list"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class=" col-xs-12 col-sm-9">
        <div class="widget-box" id="divformulacontent">
            <div class="widget-header widget-header-small widget-header-flat">
                <h6 class="widget-title">公式设置</h6>
                <div class="widget-toolbar">
                    <button id="btnValidate" class="btn btn-xs btn-link">
                        <i class="ace-icon fa fa-check"></i>
                        校验
                    </button>
                </div>
                <div class="widget-toolbar">
                    <div class="inline dropdown-hover">
                        <a href="#" data-toggle="dropdown" aria-expanded="true">
                            <i class="ace-icon fa fa-superscript"></i>
                        </a>
                        <div class="dropdown-menu dropdown-warning dropdown-menu-right dropdown-caret dropdown-close">
                            <ul>
                                <li>
                                    <a href="javascript:void(0)" data-provider="fap-formula" data-handler=" [向上取整](字段) ">取整(向上)</a>
                                </li>
                                <li>
                                    <a href="javascript:void(0)" data-provider="fap-formula" data-handler=" [向下取整](字段) ">取整(向下)</a>
                                </li>
                                <li class="divider"></li>
                                <li>
                                    <a href="javascript:void(0)" data-provider="fap-formula" data-handler=" [四舍五入](字段,精度) ">四舍五入</a>
                                </li>

                                <li>
                                    <a href="javascript:void(0)" data-provider="fap-formula" data-handler=" [绝对值](字段) ">绝对值</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="widget-toolbar">
                    <div class="inline dropdown-hover">
                        <a href="#" data-toggle="dropdown" aria-expanded="true">
                            <i class="ace-icon fa fa-bars"></i>
                        </a>
                        <div class="dropdown-menu dropdown-warning dropdown-menu-right dropdown-caret dropdown-close scrollable" data-size="300">
                            <ul>
                                @foreach (var col in columns)
                                {
                                    <li>
                                        <a href="javascript:void(0)" data-provider="fap-formula" data-handler="{@col.ColComment}">@col.ColComment</a>
                                    </li>

                                }
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="widget-toolbar">
                    <button id="btnMapping" class="btn btn-xs btn-link">
                        <i class="ace-icon fa fa-exchange"></i>
                        引用
                    </button>
                </div>
            </div>
            <div class="widget-body">
                <div class="widget-main no-padding">

                    <textarea id="formulaContent" rows="3"></textarea>

                </div>
            </div>
        </div>
        <div class="row clearfix" style="margin:0">
            <h6 class="header smaller lighter ">运算符</h6>
            <div class="col-xs-12">
                <div class="btn-group">
                    <button class="btn-light btn-sm btn btn-round" type="button" title="加"  data-provider="fap-formula" data-handler="+"><span>+</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="减"  data-provider="fap-formula" data-handler="-"><span>-</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="乘"  data-provider="fap-formula" data-handler="*"><span>*</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="除"  data-provider="fap-formula" data-handler="/"><span>/</span> </button>
                </div>
                <div class="btn-group">
                    <button class="btn-light btn-sm btn btn-round" type="button" title="大于"  data-provider="fap-formula" data-handler=">"><span>></span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="大于等于"  data-provider="fap-formula" data-handler=">="><span>>=</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="小于"  data-provider="fap-formula" data-handler="<"><span><</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="小于等于"  data-provider="fap-formula" data-handler="<="><span><=</span> </button>
                </div>

                <div class="btn-group">
                    <button class="btn-light btn-sm btn btn-round" type="button" title="等于"  data-provider="fap-formula" data-handler="="><span>=</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="不等于"  data-provider="fap-formula" data-handler="!="><span>!=</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="左小括号"  data-provider="fap-formula" data-handler="("><span>(</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="右小括号"  data-provider="fap-formula" data-handler=")"><span>)</span> </button>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-light btn-sm btn-round" title="1" data-provider="fap-formula" data-handler="1">1</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="2" data-provider="fap-formula" data-handler="2">2</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="3" data-provider="fap-formula" data-handler="3">3</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="4" data-provider="fap-formula" data-handler="4">4</button>
                </div>
                <div class="space-2"></div>
                <div class="btn-group">

                    <button type="button" class="btn btn-light btn-sm btn-round" title="5" data-provider="fap-formula" data-handler="5">5</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="6" data-provider="fap-formula" data-handler="6">6</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="7" data-provider="fap-formula" data-handler="7">7</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="8" data-provider="fap-formula" data-handler="8">8</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="9" data-provider="fap-formula" data-handler="9">9</button>
                    <button type="button" class="btn btn-light btn-sm btn-round" title="0" data-provider="fap-formula" data-handler="0">0</button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="且"  data-provider="fap-formula" data-handler="[且]"><span>且</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="或"  data-provider="fap-formula" data-handler="[或]"><span>或</span> </button>
                </div>

                <div class="btn-group">
                    <button class="btn-light btn-sm btn btn-round" type="button" title="多条件赋值" data-provider="fap-formula" data-handler="multicondition"><span>多条件赋值</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="条件" data-provider="fap-formula" data-handler="[条件]"><span>条件</span> </button>
                    @*<button class="btn-light btn-sm btn btn-round" type="button" title="<="  data-provider="fap-formula" data-handler=" NOT "><span>not</span> </button>*@
                    <button class="btn-light btn-sm btn btn-round" type="button" title="空函数" data-provider="fap-formula" data-handler="[空](字段,0)"><span>空函数</span> </button>
                    <button class="btn-light btn-sm btn btn-round" type="button" title="累计函数" data-provider="fap-formula" data-handler="[累计](字段)"><span>累计函数</span> </button>
                </div>

                <div class="space-2"></div>
            </div>
        </div>
    </div>
</div>


<script>
    $(function () {
        setTimeout(function () {
            $('.scrollable').each(function () {
                var $this = $(this);
                $(this).ace_scroll({
                    size: $this.attr('data-size') || 300,
                    //styleClass: 'scroll-left scroll-margin scroll-thin scroll-dark scroll-light no-track scroll-visible'
                });
            });
        }, 0);     
        //添加公式套btnAddFormulaCase
        $("#btnAddFormulaCase").on(ace.click_event, function () {
            bootbox.prompt("公式套名称", function (result) {
                if (result === null||result==='') {
                } else {
                    $.post("@Url.Content("~/Core/Api/FormulaCase")", { FcName: result, TableName: '@tableName' }, function (rv) {
                        if (rv.success) {
                            let data = rv.data;
                            $("#field-select-formulacase").append("<option value='" + data.fid + "'>" + data.fcName + "</option>");
                            $.msg(rv.msg);
                        } else {
                            bootbox.alert(rv.msg);
                        }
                    })
                }
            });

        })
        $("#btnEditFormulaCase").on(ace.click_event, function () {
            var fcUid = $("#field-select-formulacase").val();
            if (fcUid === '') {
                bootbox.alert("请选中公式套再修改！");
                return;
            }
            var fcName= $("#field-select-formulacase").find("option:selected").text();
            bootbox.prompt({
                title: "修改公式套名称",
                message: "公式套名称",
                value:fcName,
                callback: function (result) {
                    if (result != null) {
                        $.post("@Url.Content("~/Core/Api/FormulaCase")", { Fid: fcUid, FcName: result, TableName: '@tableName' }, function (rv) {
                            if (rv.success) {
                                $.msg(rv.msg);
                                let data = rv.data;
                                $("#field-select-formulacase").find("option:selected").text(data.fcName);
                            } else {
                                bootbox.alert(rv.msg);
                            }
                        })
                    }
                }
            })
        })
        //删除工资套
        $("#btnDelFormulaCase").on(ace.click_event, function () {
            var fcUid = $("#field-select-formulacase").val();
            if (fcUid === '')
            {
                bootbox.alert("请选中公式套再删除！");
                return;
            }
            bootbox.confirm("确定要删除选中的公式套?", function (result) {
                if (result) {
                    $.delete("@Url.Content("~/Core/Api/FormulaCase/")" + fcUid, function (rv) {
                        if (rv.success) {
                            $.msg(rv.msg);
                            $("#field-select-formulacase").find("option:selected").remove();
                            $("#field-select-formulacase").change();
                        } else {
                            bootbox.alert(rv.msg);
                        }
                    })
                }
            });

        })
        $("#field-select-formulacase").change(function () {
            var fcuid = $(this).val();
            $("#formulaItems").children("li").remove();
            //已有公式项
            $.get("@Url.Content("~/Core/Api/FormulaItems/")" + fcuid, function (rv) {
                if (!rv.success) {
                    bootbox.alert(rv.msg);
                    return;
                }
                let data = rv.data;
                $.each(data, function (i, d) {
                    if (d.fmuDesc === '' || d.fmuDesc===null) {
                        var str = '<li class="item-orange clearfix">';
                    }
                    else {
                        str = '<li class="item-green clearfix">';
                    }
                    str+=d.colComment +
                                     '<div class="pull-right action-buttons">' +
                                     '<a href="javascript:void(0)" title="启用" class="green">';
                    if (d.enabled == 1) {
                        str += '<i class="ace-icon fa fa-check-square-o bigger-130"></i>';

                    } else {
                        str += ' <i class="ace-icon fa  fa-square-o bigger-130"></i>';
                    }
                    str += '  </a> </div>' + ' </li>';
                    var $str = $(str);
                    //对象赋值data
                    $str.data("fmudata", JSON.stringify(d));
                    //操作标识
                    //$str.data("oper", "default");
                    $("#formulaItems").append($str);
                });

            })
        })
        //公式编辑器
        var formulaEditor = CodeMirror.fromTextArea(document.getElementById("formulaContent"), {
            mode: 'text/x-mssql',
            theme: 'xq-light',
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            autofocus: true,

        });
        //校验公式项
        $("#btnValidate").on(ace.click_event, function () {
            var fmuItems = [];
            var $this = $("#formulaItems li").filter(".selected");
            var fmudataStr = $this.data("fmudata");
            if (fmudataStr == undefined) {
                return;
            }
            var fmudata = JSON.parse(fmudataStr);

            $.post("@Url.Content("~/Core/Api/VerifyFormula")", { entity: '@tableName', mappingEntity:'@mappingTableName', verfiyField: fmudata.colName, verfiyContent: fmudata.fmuDesc }, function (rv) {
                if (rv.success) {
                    $.msg("公式校验合法！" + rv.data);
                } else {
                    bootbox.alert(rv.msg);
                }
            });
        });
        var formulaHasChange = false;
        //保存公式项
        $("#btnSaveFormulaItem").on(ace.click_event, function () {
            var fmuItems = [];
            var fcUid = $("#field-select-formulacase").val();
            if (fcUid === '')
            {
                $.msg("请选择要保存得公式套！");
                return;
            }
            $("#formulaItems li").each(function (i) {
                var fmudataStr = $(this).data("fmudata");
                var fmudata = JSON.parse(fmudataStr);
                fmudata.orderBy = i;
                fmuItems.push(fmudata);
            });
            if (fmuItems.length < 1) {
                $.msg("请设置要保存得公式项");
                return;
            }
            $.post("@Url.Content("~/Core/Api/Formula/")", { mappingTable:'@mappingTableName',tableName: '@tableName',fcUid:fcUid, formulas: fmuItems }, function (rv) {
                if (rv.success) {
                    $.msg(rv.msg);
                    formulaHasChange = false;
                } else {
                    bootbox.alert(rv.msg);
                }
            });

        });
        //公式内容变化的时候 及时赋值data对象
        formulaEditor.on("change", function (instance) {
            var $currLi = $("#formulaItems li").filter(".selected");
            var fmudataStr = $currLi.data("fmudata");
            if (fmudataStr == undefined)
            {
                return;
            }
            var fmudata = JSON.parse(fmudataStr);
            if (fmudata != undefined) {
                if (fmudata.fmuDesc === null) {
                    fmudata.fmuDesc = "";
                }
                if (fmudata.fmuDesc != instance.getValue()) {
                    //公式项有变化
                    formulaHasChange = true;
                    $.msg("公式有变化,请保存公式项");
                }
                fmudata.fmuDesc = instance.getValue();
                if ($currLi.hasClass("item-orange") && fmudata.fmuDesc !== '') {
                    $currLi.removeClass("item-orange");
                    $currLi.addClass("item-green");
                }
                if ($currLi.hasClass("item-green") && fmudata.fmuDesc === '') {
                    $currLi.removeClass("item-green");
                    $currLi.addClass("item-orange");
                }
            }
            $currLi.data("fmudata", JSON.stringify(fmudata));
            
        });
        //操作符插入
        $(":button[data-provider='fap-formula']").on(ace.click_event, function () {
            var handler= $(this).data("handler");
            if (handler === "multicondition") {
                handler = `[多条件赋值]
[当]   条件值1   [取]  结果1
[当]   条件值2    [取]  结果2
[否则] 默认结果  [结束]`;
            } 
            formulaEditor.replaceSelection(handler.toString());
        });
        $("a[data-provider='fap-formula']").on(ace.click_event, function () {
            formulaEditor.replaceSelection($(this).data("handler").toString());
        });
        //公式项排序
        $('#formulaItems').sortable({
            opacity: 0.8,
            revert: true,
            forceHelperSize: true,
            placeholder: 'draggable-placeholder',
            forcePlaceholderSize: true,
            tolerance: 'pointer',
            stop: function (event, ui) {
                //just for Chrome!!!! so that dropdowns on items don't appear below other items after being moved
                $(ui.item).css('z-index', 'auto');
            }
        });
        //设置公式禁用
        $(document).off(ace.click_event, "#formulaItems li a").on(ace.click_event, "#formulaItems li a", function (e) {
            //阻止a的默认事件
            e.preventDefault();
            //阻止冒泡事件
            e.stopPropagation();
            if ($(this).find("i").hasClass("fa-check-square-o")) {
                $(this).find("i").removeClass("fa-check-square-o");
                $(this).find("i").addClass("fa-square-o");
                var fmudataStr = $(this).closest("li").data("fmudata");
                var fmudata = JSON.parse(fmudataStr);
                fmudata.enabled = 0;
                $(this).closest("li").data("fmudata", JSON.stringify(fmudata));
            } else {
                $(this).find("i").removeClass("fa-square-o");
                $(this).find("i").addClass("fa-check-square-o");
                var fmudataStr = $(this).closest("li").data("fmudata");
                var fmudata = JSON.parse(fmudataStr);
                fmudata.enabled = 1;
                $(this).closest("li").data("fmudata", JSON.stringify(fmudata));
            }
            return false;
        });
        //公式项选中设置公式
        $(document).off(ace.click_event, "#formulaItems li").on(ace.click_event, "#formulaItems li", function () {
            $("#formulaItems li").each(function () {
                $(this).removeClass('selected');
            });
            $(this).addClass('selected');
            var fmudataStr = $(this).data("fmudata");
            var fmudata = JSON.parse(fmudataStr);
            if (fmudata == undefined) {
                fmudata = {};
                fmudata.fmuDesc = '';
            }
            if (fmudata.fmuDesc === null || fmudata.fmuDesc === undefined)
            {
                fmudata.fmuDesc = '';
            }
            formulaEditor.getDoc().setValue(fmudata.fmuDesc);
            formulaEditor.refresh();
        });

        //添加公式项
        $("#btnAddFormulaItem").on(ace.click_event, function () {
            var fcase = $("#field-select-formulacase").val();
            if (fcase === '') {
                $.msg("请选择公式套");
                return;
            }
            //获取已有的公式项设置选中
            var exist = [];
            $("#formulaItems li").each(function () {
                var fmudataStr = $(this).data("fmudata");
                var fmudata = JSON.parse(fmudataStr);
                exist.push(fmudata.colName);
            });
            var formulaItems;
            var dialog=  bootbox.dialog({
                title: "添加公式项.",
                message: '<select multiple="multiple" size="10" id="duallistbox_formulaitems" name="duallistbox_formulaitems"></select>',
                buttons: {
                    success: {
                        label: "确定",
                        className: "btn-primary",
                        callback: function () {
                            var vals = $("#duallistbox_formulaitems").val();
                            if (vals == '') {
                                bootbox.alert("没有要添加的项！")
                            } else {
                                //获取选中项json
                                var filterVals = $.grep(formulaItems, function (rd, i) {
                                    return $.inArray(rd.colName, vals) > -1;
                                });
                                //如果这次没选则移除现有公式项
                                $("#formulaItems li").each(function () {
                                    var fmudataStr = $(this).data("fmudata");
                                    var fmudata = JSON.parse(fmudataStr);
                                    if ($.inArray(fmudata.colName, vals) < 0) {
                                        $(this).remove();
                                    }
                                });
                                $.each(filterVals, function (i, d) {
                                    if ($.inArray(d.colName, exist) > -1) {
                                        //列表中已存在
                                    } else {
                                        //不存在就新增
                                        var str = '<li class="item-orange clearfix">' +
                                        d.colComment +
                                        '<div class="pull-right action-buttons">' +
                                            '<a href="javascript:void(0)" title="启用" class="green">' +
                                                '<i class="ace-icon fa fa-check-square-o bigger-130"></i>' +
                                           ' </a>' +
                                       ' </div>' +
                                   ' </li>';

                                        var fd = { tableName: '@tableName', colName: d.colName, colComment: d.colComment, fmuContent: '', fmuDesc: '', enabled: 1, Fid: '' }
                                        var $str = $(str);
                                        var fmudataStr = JSON.stringify(fd);
                                        $("#formulaItems").append($str);
                                        $str.data("fmudata", fmudataStr);
                                    }
                                });

                            }
                        }
                    },
                    cancel: {
                        label: "取消", className: "btn-default"
                    }
                }
            });
            dialog.init(function () {
                $.get("@Url.Content("~/Core/Api/FieldList/")@tableName", function (data) {
                    $("#duallistbox_formulaitems").empty();
                    var fitems = $.grep(data, function (sd, i) {
                        return sd.isDefaultCol == 0;
                    });
                    formulaItems = fitems;
                    $.each(fitems, function (i, d) {
                        var strSel = '';
                        if ($.inArray(d.colName, exist) > -1) {
                            strSel = 'selected = "selected"';
                        }
                        $("#duallistbox_formulaitems").append("<option value='" + d.colName + "' " + strSel + ">" + d.colComment + "</option>");
                    });
                    $('#duallistbox_formulaitems').bootstrapDualListbox({
                        nonSelectedListLabel: '<span class="text-primary h5">所有项</span> ',
                        selectedListLabel: '<span class="text-primary h5">选中项</span> ',
                        preserveSelectionOnMove: 'moved',
                        moveOnSelect: true

                    });
                })
            });
        });
        $("#btnMapping").on(ace.click_event, function () {
            var $currLi = $("#formulaItems li").filter(".selected");
            if ($currLi === undefined) {
                $.lang("please_select_formulaitem", "请选中公式项设置");
                return;
            }         
            var dialog = bootbox.dialog({
                title: $.lang("mapping", "引用"),
                message: '<p><i class="fa fa-spin fa-spinner"></i> Loading...</p>',
                buttons: {
                    success: {
                        label: $.lang("ok", "确定"),
                        className: "btn-primary",
                        callback: function () {                          
                            let mapping = getMappingResult();                           
                            formulaEditor.getDoc().setValue(mapping);                          
                        }
                    },
                    cancel: {
                        label: $.lang("cancel", "取消"), className: "btn-default"
                    }
                }
            });
            dialog.init(function () {
                $.get("@Url.Content("~/Component/FieldMapping/")?oriEntity=@mappingTableName", function (rv) {
                    dialog.find('.bootbox-body').html(rv);
                })
            });
        })
    })
</script>